package com.skp.shaphan.toolbars;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JComboBox;

import com.skp.job.ProjectJobException;
import com.skp.shaphan.ShaphanApp;

public class CatalogSelector extends JComboBox implements ItemListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5204496619368633583L;

	public CatalogSelector() {
		this.addItemListener(this);
	}
	
	public void loadCatalogs() {
		this.removeAllItems();
		ShaphanApp app = ShaphanApp.getMainWindow();
		Connection conn = app.getSQLEditorsPane().getConnection().getConnection();
		try {
			DatabaseMetaData metaData = conn.getMetaData();
			ResultSet rs = metaData.getCatalogs();
			if(rs != null) {
				while(rs.next()) {
					this.addItem(rs.getString(1));
					if(rs.getString(1).equals(conn.getCatalog())) {
						this.setSelectedIndex(this.getItemCount() - 1);
					}
				}
				rs.close();
			}
		} catch (SQLException e) {
			if(e.getMessage().toLowerCase().indexOf("driver not capable") >= 0) {
				// we should do nothing at this point -- it just means that the database doesn't have
				// catalogs
			} else {
				(new ProjectJobException(e)).displayException();
			}
		}
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		String selectedCatalog = this.getSelectedItem().toString();
		ShaphanApp app = ShaphanApp.getMainWindow();
		Connection conn = app.getSQLEditorsPane().getConnection().getConnection();
		try {
			conn.setCatalog(selectedCatalog);
		} catch (SQLException e1) {
			(new ProjectJobException(e1)).displayException();
		}
	}
}
